package httpresult

import (
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/trace"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"net/http"
)

// http返回
func HttpResult(r *http.Request, w http.ResponseWriter, req interface{}, resp interface{}, err error) {
	if err == nil {
		//成功返回
		//logx.WithContext(r.Context()).Infof("【API-OK】 req_path:%s req:%+v", r.URL.Path, req)
		//logx.WithContext(r.Context()).Infof("【API-OK】 resp_path:%s resp:%+v", r.URL.Path, resp)
		rsp := Success(resp, trace.TraceIDFromContext(r.Context()))
		httpx.OkJsonCtx(r.Context(), w, rsp)
		return
	}
	logx.WithContext(r.Context()).Errorf("【API-ERR】 req_path:%s err:%+v req:%+v", r.URL.Path, err, req)

	//错误返回
	errcode := xerr.ServerCommonError
	errmsg := "system error"

	if utils.IsZeroAddressesError(err) {
		// 如果返回的是零地址错误，则返回空值
		logx.WithContext(r.Context()).Errorf("--------error: produced zero addresses-------------")
		httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, Error(errcode, errmsg, trace.TraceIDFromContext(r.Context())))
		return
	}

	gstatus, ok := status.FromError(err)
	if ok { // grpc err错误
		//区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
		errcode = uint32(gstatus.Code())
		if errcode != xerr.DbError {
			errmsg = gstatus.Message()
		} else {
			errmsg = "system internal error"
		}
	}

	logx.WithContext(r.Context()).Errorf("【API-ERR】 path:%s err code:%d msg:%s", r.URL.Path, errcode, errmsg)
	httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, Error(errcode, errmsg, trace.TraceIDFromContext(r.Context())))
	return
}

// http 参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, Error(xerr.RequestParamError, err.Error(), trace.TraceIDFromContext(r.Context())))
}
